package cn.shadowsouls.system.manger.impl;

import cn.shadowsouls.common.exception.DefinitionException;
import cn.shadowsouls.system.bean.AuthorizationSet;
import cn.shadowsouls.system.bean.LoginData;
import cn.shadowsouls.system.bean.RegisterData;
import cn.shadowsouls.system.bean.domain.User;
import cn.shadowsouls.system.manger.UserManger;
import cn.shadowsouls.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 有关于用户的操作
 *
 * @author shadowsouls
 * @version 1.0
 */

@Component
public class UserMangerImpl implements UserManger {


    final UserService userService;

    @Autowired
    public UserMangerImpl(UserService userService) {
        this.userService = userService;
    }


    @Override
    public boolean login(LoginData data) {


        String code = String.valueOf(getAuthorCode(data));

        // 确认是否放入授权码
        if (!AuthorizationSet.existAuthor(code)) {
            return AuthorizationSet.addAuthor(
                    String.valueOf(getAuthorCode(data))
            );
        }


        return false;
    }

    @Override
    public boolean logout(String authorCode) {

        // if (AuthorizationSet.existAuthor(authorCode))
        return AuthorizationSet.removeAuthor(authorCode);

        // throw new DefinitionException(500, "未获取授权");
    }

    @Override
    public boolean register(RegisterData data) {

        if (data.validData() && !exitUser(data.getUsername())) {
            userService.save(new User(data.getUsername(), data.getPassword()));
            return true;
        }
        return false;
    }


    @Override
    public boolean exitUser(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper
                .select("username")
                .eq("username", username);
        if (userService.count(queryWrapper) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Integer getAuthorCode(LoginData data) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        System.out.printf(data.toString());

        queryWrapper.lambda()
                .eq(User::getUsername, data.getUsername())
                .eq(User::getPassword, data.getPassword());
        try {
            return userService.getOne(queryWrapper).getUserId();
        } catch (RuntimeException e) {
            throw new DefinitionException(500, "账号密码错误");
        }
    }

    @Override
    public boolean isLogin(String authorCode) {
        return AuthorizationSet.existAuthor(authorCode);
    }

}
